package com.zzzzzz.content.topic;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zzzzzz.account.user.UserBase;
import com.zzzzzz.common.util.Constants;
import com.zzzzzz.common.util.FileUtils;
import com.zzzzzz.core.data.filestore.FileData;
import com.zzzzzz.core.data.filestore.FileStorage;


@Service("topicService")
public class TopicServiceImpl implements TopicService {

	@Resource
	private TopicDao topicDao;
	@Resource
	private FileStorage fileStorage;
	
	@Override
	public String add(UserBase userBase, TopicForm topicForm) throws IOException {
		String userId = userBase.getUserId().toString();
		Date now = new Date();
		
		Topic topic = new Topic();
		topicForm.updateTopic(topic);
		topic.setUserId(userId);
		topic.setAddDt(now);
		topic.setUpdDt(now);
		topic.setStatus(0);
		
		if(topicForm.getFiles().getSize()>0){
			this.storeFile(topicForm.getFiles(), topic);
		}
		
		topic.setUserBase(userBase);
		
		topicDao.add(topic);
		return topic.getTopicId();
	}
	
	private void storeFile(CommonsMultipartFile files, Topic topic) throws IOException{
		if(files != null) {
			// actual image
			FileData imageData = FileUtils.getResizedImageData(files, Constants.IMAGE.TOPIC_MAX_WIDTH, Constants.IMAGE.TOPIC_MAX_HEIGHT, false);
			String imageId = fileStorage.storeFile(imageData);
			topic.setImgId(imageId);
			// thumbnail
			FileData thumbnailData = FileUtils.getResizedImageData(files, Constants.IMAGE.TOPIC_THUMBNAIL_MAX_WIDTH, Constants.IMAGE.TOPIC_THUMBNAIL_MAX_HEIGHT, false);
			String thumbnailId = fileStorage.storeFile(thumbnailData);
			topic.setImgSId(thumbnailId);
		}
	}

	@Override
	public void edit(String userId, String topicId, TopicForm topicForm) throws IOException {
		Date now = new Date();
		
		Topic topic = new Topic();
		topicForm.updateTopic(topic);
		topic.setTopicId(topicId);
		topic.setUserId(userId);
		topic.setUpdDt(now);
		
		if(topicForm.getFiles().getSize()>0){
			this.storeFile(topicForm.getFiles(), topic);
		}
		
		topicDao.edit(topic);
	}
	
	@Override
	public Topic findById(String topicId) throws NoSuchTopicException {
		return topicDao.findById(topicId);
	}
	
	@Override
	public void editStatus(String userId, String topicId, Integer status) {
		topicDao.editStatus(userId, topicId, status);
	}
}
